package com.tangsm.boot.demo.shiro.simple;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@SuppressWarnings("deprecation")
public class Tutorial {
        private static final transient Logger log = LoggerFactory.getLogger(Tutorial.class);

        public static void main(String[] args) {
            log.info("My First Apache Shiro Application");
            // SecurityManager： Shiro的心脏；所有具体的交互都通过SecurityManager进行控制；负责所有Subject、且负责进行认证和授权、及会话、缓存的管理。
            // Authenticator：认证器，判断用户是否正常登陆
            // Authorizer：授权器，判断用户是否有权限操作资源
            Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
            SecurityManager securityManager = factory.getInstance();
            // 设置静态用户
            SecurityUtils.setSecurityManager(securityManager);
            // 获取当前正在执行的用户
            Subject currentUser = SecurityUtils.getSubject();
            // 用会话做些事情（不需要web或EJB容器！！！）
            Session session = currentUser.getSession();
            session.setAttribute("someKey", "aValue");
            // 获取已登录用户
            String value = (String) session.getAttribute("someKey");
            if (value.equals("aValue")) {
                log.info("Retrieved the correct value! [" + value + "]");
            }
            // 判断用户是否已经认证
            if (!currentUser.isAuthenticated()) {
            	// 用户登录凭证
                UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
                // 记住我
                token.setRememberMe(true);
                try {
                	// 登陆校验
                    currentUser.login(token);
                } catch (UnknownAccountException uae) {
                    log.info("There is no user with username of " + token.getPrincipal());
                } catch (IncorrectCredentialsException ice) {
                    log.info("Password for account " + token.getPrincipal() + " was incorrect!");
                } catch (LockedAccountException lae) {
                    log.info("The account for username " + token.getPrincipal() + " is locked.  "
                            + "Please contact your administrator to unlock it.");
                } 
                // ... catch more exceptions here (maybe custom ones specific to your application?
                catch (AuthenticationException ae) { 
                	// unexpected condition? error?
                }
            }
            // say who they are:
            // print their identifying principal (in this case, a username):
            log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
            // 判断是否有角色权限
            if (currentUser.hasRole("schwartz")) {
                log.info("May the Schwartz be with you!");
            } else {
                log.info("Hello, mere mortal.");
            }
            // 判断是否有资源操作权限
            if (currentUser.isPermitted("lightsaber:wield")) {
                log.info("You may use a lightsaber ring.  Use it wisely.");
            } else {
                log.info("Sorry, lightsaber rings are for schwartz masters only.");
            }
            // a (very powerful) Instance Level permission:
            if (currentUser.isPermitted("winnebago:drive:eagle5")) {
                log.info(
                        "You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  "
                                + "Here are the keys - have fun!");
            } else {
                log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
            }
            // 登出
            currentUser.logout();
            System.exit(0);
        }
    }